package com.java.netty.groupchat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.Date;

/**
 * @author jl
 * Created on 2020/9/30
 */
public class GroupChatServerHandler extends SimpleChannelInboundHandler<String> {

    // channel集合
    private static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    // 建立连接,第一个被执行
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channels.writeAndFlush("玩家[" + channel.remoteAddress() + "]进入服务器 " + new Date() + "\n");
        channels.add(channel);
        System.out.println("玩家[" + channel.remoteAddress() + "]进入服务器 " + new Date());
    }

    // 断开连接
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println("玩家[" + channel.remoteAddress() + "]离开服务器 " + new Date());
    }

    // 连接出于活动状态
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channels.forEach(ch -> {
            if (ch != channel) {
                ch.writeAndFlush("您的好友[" + channel.remoteAddress() + "]上线了\n");
            }
        });
    }

    // 连接出于不活动状态
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        // 将客户端连接的消息推送给其他在线的客户端
        channels.writeAndFlush("您的好友[" + channel.remoteAddress() + "]下线了\n");
    }

    // 读取数据
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        Channel channel = ctx.channel();
        channels.forEach(ch -> {
            if (ch != channel) {
                ch.writeAndFlush("好友[" + channel.remoteAddress() + "]发送消息:" + msg + "\n");
            }
        });
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
